package csc.daonjpa.java.controller;

import java.util.List;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.service.AccountService;
import csc.daonjpa.java.service.CardService;
import csc.daonjpa.java.service.CustomerService;

@Controller
public class CustomerController {
	private static final Logger LOG = Logger.getLogger(AccountController.class);
	
	@Autowired
	private AccountService bankService;
	
	@Autowired
	private CardService cardService;
	
	@Autowired
	private CustomerService customerService;
	
	/**
	 * go to register customer page.
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/register")
	public ModelAndView getHome(Model model) {
		return new ModelAndView("customer");
	}
	
	/**
	 * Adds customer to DB
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/createCustomer")
	public String addCustomer(HttpServletRequest request, Model model) {
		// Read account info from request and save into Account object
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		Customer customer = new Customer ( loginId, password, firstName, lastName, address, phone);
		try {
			// Save account to DB
			customerService.addCustomer(customer);
			model.addAttribute("successMessage",
					"Successfully registered. Please click on login");
		} catch (PersistenceException ex) {
			if (ex.getCause() instanceof ConstraintViolationException) {
				model.addAttribute("errorMessage", "Duplicated account found");
			} else {
				model.addAttribute("errorMessage", "Error adding new customer");
			}
			LOG.error("Error found adding an customer", ex);
			throw ex;
		} catch (Exception e) {
			LOG.error("General Error found adding an customer", e);
			throw e;
		}
		
		return "customer";
	}
	/**
	 * get list customers
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/listCustomer")
	public ModelAndView getCustomerList(Model model) {

		// Get the list of all accounts from DB
		List<Customer> customerList = customerService.getCustomers();
		ModelAndView modelAndView = new ModelAndView("customerList");
		modelAndView.addObject("listCustomers",customerList );
		return modelAndView;
	}
	
	/**
	 * Login in system
	 * @param model
	 * @return
	 */
	
	@RequestMapping(value = "/login", method = RequestMethod.POST) 
	public String loginPage(HttpServletRequest request ,Model model) {
		HttpSession session = request.getSession();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		Integer check = customerService.checkLogin(username, password);
		String nextPage = "";
		if (check.equals(1)) {
			session.setAttribute("loginSession", username);
			nextPage = "home";
			return nextPage;
		} else {
			model.addAttribute("error", "The username or password you entered is incorrect.");
			nextPage = "login";
		}
		return nextPage;
	}
	/**
	 * Log out
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/logout") 
	public String logout( Model model,HttpSession session) {
		session.invalidate();
		return "forward:/";
	}
	/**
	 * go to edit customer page
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/editCustomer")
	public String editCustomer(HttpSession session, Model model) {
		 String loginId = session.getAttribute("loginSession").toString();
		 Customer customer = customerService.getCustomer(loginId);
		 model.addAttribute("customer",customer);
		 return "editCustomer";
	}
	/**
	 * update user's information 
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/modifyCustomer", method = RequestMethod.POST)
	public String updateCustomer(HttpServletRequest request,Model model) {
		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		String loginId = request.getParameter("loginId");
		String password = request.getParameter("password");
		Long id = customerService.getCustomer(loginId).getId();
		Customer customer = new Customer(id, loginId, password, firstName, lastName, address, phone);
		try {
			// Save account to DB
		    customerService.updateCustomer(customer);
			model.addAttribute("successMessage",
					"Modify Customer Information  successfully");
		} catch (PersistenceException ex) {
				model.addAttribute("errorMessage", "Error");
			
			LOG.error("Error", ex);
			throw ex;
		} catch (Exception e) {
			LOG.error("General Error", e);
			throw e;
		}
		return "forward:/editCustomer";
	}
	/**
	 * go to the change password page
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "changePassword")
	public ModelAndView passwordPage(Model model) {
		return new ModelAndView("password");
	}
	/**
	 * update password 
	 * @param session
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "updatePassword", method = RequestMethod.POST)
	public String updatePassowrd (HttpSession session, HttpServletRequest request, Model model) {
		String loginId = session.getAttribute("loginSession").toString();
		Customer customer = customerService.getCustomer(loginId);
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		String confirmPassword = request.getParameter("confirmPassword");
		boolean check = customerService.updatePassword(oldPassword, customer.getPassword(), newPassword, confirmPassword, customer.getId());
		if (check == true) {
			model.addAttribute("successMessage",
					"Change password successfully");
		} else {
			model.addAttribute("errorMessage", "The passwords do not match");
		}
		return "password";
	}
	/**
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception ex) {
 
		ModelAndView model = new ModelAndView("login");
		model.addObject("errorMessage", "Exception occurred");
 
		return model;
	}
}
